"""
FastAPI 应用配置
"""

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
import logging

from .api.routes import router
from .core.config import settings
from .core.logging import setup_logging

# 设置日志系统
setup_logging(settings.LOG_LEVEL)
logger = logging.getLogger(__name__)

def create_app() -> FastAPI:
    """创建 FastAPI 应用"""
    
    app = FastAPI(
        title="对话处理服务",
        description="基于FunASR的音频转录和需求分析服务",
        version="1.0.0",
        docs_url="/docs",
        redoc_url="/redoc"
    )
    
    # CORS 中间件
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.ALLOWED_HOSTS or ["*"],
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
    
    # Gzip 压缩中间件
    app.add_middleware(GZipMiddleware, minimum_size=1000)
    
    # 包含路由
    app.include_router(router, prefix="/api/v1")
    
    @app.on_event("startup")
    async def startup_event():
        """应用启动事件"""
        logger.info("对话处理服务启动")
        
        # 确保必要目录存在
        for directory in [settings.UPLOAD_DIR, settings.OUTPUT_DIR, settings.LOGS_DIR, settings.MODELS_DIR]:
            directory.mkdir(parents=True, exist_ok=True)
            logger.info(f"确保目录存在: {directory}")
    
    @app.on_event("shutdown")
    async def shutdown_event():
        """应用关闭事件"""
        logger.info("对话处理服务关闭")
    
    @app.get("/")
    async def root():
        """根路径"""
        return {
            "message": "对话处理服务",
            "version": "1.0.0",
            "status": "running",
            "docs_url": "/docs",
            "health_check": "/api/v1/health"
        }
    
    return app

# 创建应用实例
app = create_app()